var app = getApp()
var api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value1: 1,
    transExpense: 8,
    money: 0,
    lists: [],

    ordlists: [],

    addreslist: {},
    orderDetailsList: [],
    discounts: 0,
    totalPrice: 0,
    totalNum: 0,
    buytp: '代购',
    comment: '',

  },



  adres: function (e) {
    wx.navigateTo({
      url: '/pages/adressmg/adressmg',
    })
  },

  buytp: function (e) {
    var that = this
    var list = ['代购', '自购']
    wx.showActionSheet({
      itemList: ['代购', '自购'],
      success: function (res) {
        if (!res.cancel) {
          console.log(res.tapIndex)
          that.setData({
            buytp: list[res.tapIndex]
          })
        }
      }
    });
  },

  realnameConfirm: function (e) {
    var that = this;
    that.setData({
      comment: e.detail.value
    })
  },


  purchase: function (e) {
    var that = this;
    wx.showModal({
      title: '交易提示',
      content: '是否确认提交订单？',
      confirmColor: "#43CBC9",
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })

        if (that.data.buytp == '自购') {
          var buyType = '1' //购买类型
        } else if (that.data.buytp == '代购') {
          var buyType = '2' //购买类型
        }
        var goodsSales = that.data.totalPrice //商品总价
        var transportationExpense = that.data.transExpense //运费
        var orderSales = 500 //订单总价
        var actualPayment = that.data.money //实际支付金额
        var comment = that.data.comment//备注
        var addressId = that.data.addreslist.id;
        console.log('addressId' + addressId)
        var status = '' //订单状态
        var discounts = that.data.discounts

        var orderDetailsList = []

        var list = that.data.ordlists.lists;
        for (var i = 0; i < list.length; i++) {
          var l = list[i];
          var temp = {
            goodsId: l.goodsId,
            goodsNum: l.num, //商品的数量
            comment: '无',  //备注
          }
          console.log(temp)
          orderDetailsList.push(temp)
        }

        console.log("orderDetailsList" + orderDetailsList)
        that.setData({
          orderDetailsList: orderDetailsList
        })

        if (res.confirm) {
          console.log('for发生了submit事件，携带数据为：', e.detail.value);

          if (addressId == undefined) {
            wx.showToast({
              title: "请完善收货信息!",
              icon: 'none',
              duration: 2000
            });
            return false;
          }
          console.log("addressId" + addressId)
          console.log("buyType" + buyType)
          console.log("comment" + comment)
          console.log("orderDetails" + orderDetailsList)

          wx.request({
            url: api.OrdersSubmit,
            data: {

              addressId: addressId,
              buyType: buyType,
              comment: comment,
              orderDetails: orderDetailsList,
              tokenType: 0
            },
            method: 'POST',
            header: {
              'Accept': 'application/json',
              'ACCESS-TOKEN': wx.getStorageSync('token')
            },

            success: function (res) {
              if (res.data.success) {
                that.droplist()

                var orderNo = res.data.obj.orderNo;
                console.log("orderNo=" + orderNo)
                wx.showModal({
                  title: '提示',
                  content: "确认是否支付？",
                  confirmColor: "#43CBC9",
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')

                      wx.request({
                        url: api.OrdersPay,
                        data: {
                          orderNo: orderNo,
                          status: '0',
                          payType: "1",
                        },
                        method: 'POST',
                        header: {
                          'Accept': 'application/json',
                          'ACCESS-TOKEN': wx.getStorageSync('token')
                        },

                        success: function (res) {
                          if (res.data.success) {
                            wx.showModal({
                              title: '交易提示',
                              content: "支付成功!",
                              confirmColor: "#43CBC9",
                              showCancel: false,
                              success: function (res) {
                                if (res.confirm) {
                                  console.log('用户点击确定')
                                  wx.switchTab({
                                    url: '/pages/shops/shops',
                                  })
                                }
                              }
                            });
                            wx.hideLoading();
                          } else {
                            wx.showToast({
                              title: res.data.msg,
                              icon: 'none',
                              duration: 3000
                            });
                          }

                        },
                        fail: function () {
                          wx.hideLoading();
                          wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            duration: 3000
                          });
                        },
                      })

                    } else if (res.cancel) {
                      wx.showModal({
                        title: '交易提示',
                        content: "订单已生成，等待支付！",
                        confirmColor: "#43CBC9",
                        showCancel: false,
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                            wx.switchTab({
                              url: '/pages/shops/shops',
                            })
                          }
                        }
                      });
                      wx.hideLoading();


                    }
                  }
                });
                wx.hideLoading();
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 3000
                });
              }

            },
            fail: function () {
              wx.hideLoading();
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 3000
              });
            },
          })

        } else
          if (res.cancel) {

            wx.showToast({
              title: "订单已取消!",
              icon: 'none',
              duration: 2000
            });

            console.log('用户点击取消')
            wx.hideLoading();
          }
      }

    })
  },

  droplist:function(){
    var that = this 
    var list = wx.getStorageSync("lists")
    var ordlis = that.data.ordlists.lists
    var ls =[]

    for (var i = 0; i < ordlis.length; i++){
      for (var j = 0; j < list.length; j++){
        if (list[j].id == ordlis[i].id){
          console.log("list[j].id" + list[j].id)
          list.splice(j,1)
        }
      }
    }
    wx.setStorageSync("lists", list)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      ordlists: wx.getStorageSync("ordlists")
    })
    that.setData({
      totalPrice: that.data.ordlists.totalPrice,
      totalNum: that.data.ordlists.totalNum,
    })

    var mon = (parseFloat(that.data.totalPrice) + 8.00).toFixed(2);
    that.setData({
      money: mon,
    })



  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    var that = this;
    that.setData({
      lists: wx.getStorageSync('lists'),
      addreslist: wx.getStorageSync('defut')
    })

    var lis = that.data.ordlists.lists
    var pris = 0
    for (var i = 0; i < lis.length; i++) {
      pris = (pris + (lis[i].marketPrice - lis[i].retailPrice) * lis[i].num).toFixed(2)
      console.log('pris' + pris)
    }
    console.log('pris' + pris)
    that.setData({
      discounts: pris
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})